﻿using JESAI.DynamicWebApi;
using JESAI.DynamicWebApi.Configurations;
using JESAI.DynamicWebApi.Conventions;
using JESAI.DynamicWebApi.Providers;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ApplicationParts;
using Microsoft.Extensions.DependencyInjection;
using Panda.DynamicWebApi.Helpers;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;

namespace Microsoft.Extensions.DependencyInjection
{
    public static class DynamicWebApiServiceCollectionExtensions
    {
        /// <summary>
        /// 注册DynamicWebApi
        /// </summary>
        /// <param name="services"></param>
        /// <param name="assembly"></param>
        /// <param name="moduleName"></param>
        /// <param name="useConventionalHttpVerbs"></param>
        /// <returns></returns>
        public static IServiceCollection AddDynamicWebApi(this IServiceCollection services, Assembly assembly,
           string moduleName = AppConsts.DefaultServiceModuleName,
           bool useConventionalHttpVerbs = true)
        {
            //TO-DO:注册多个程序集，目前应该是仅仅支持一个，其实很简单，创建链式方法Add即可
            IDynamicWebApiConfiguration dynamicWebApiConfiguration = new DynamicWebApiConfiguration();
            dynamicWebApiConfiguration.CreateControllersForAppServices(assembly,moduleName,useConventionalHttpVerbs);
            services.AddSingleton<IDynamicWebApiConfiguration>(dynamicWebApiConfiguration);
            var partManager = services.GetSingletonInstanceOrNull<ApplicationPartManager>();
            partManager?.FeatureProviders.Add(new DynamicWebApiControllerFeatureProvider(services));
            services.Configure<MvcOptions>(mvcOptions =>
            {
                AddConventions(mvcOptions,services);
            });
            return services;
        }

        private static void AddConventions(MvcOptions mvcOptions, IServiceCollection services)
        {
            mvcOptions.Conventions.Add(new DynamicWebApiAppServiceConvention(services));
        }
    }
}
